package cn.wildfire.chat.app.extendsion.ui;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.view.MotionEvent;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import androidx.recyclerview.widget.RecyclerView;

import com.sourcemuch.im.caiba.R;import com.sourcemuch.im.caiba.R2;

import java.util.HashMap;

import cn.wildfire.chat.app.extendsion.utils.TextUtils;

/**
 * Create by HEKE, 2019/9/4 11:28
 * TODO 折叠控件、上下拖动控件效果实现对象，不进行原始控件的修改(有些控件无实现功能并无法修改)
 */
public class SmoothToggleAndSlideAnimationForUI {

    /**
     * 隐藏控件标志
     */
    private static final String HIDE = "0";

    /**
     * 显示控件标志
     */
    private static final String SHOW = "1";

    /**
     * 主界面的搜索栏显示与隐藏
     */
    public static final int FLAG_MAIN = 0x00;

    /**
     * 群组增删群员搜索栏显示与隐藏
     */
    public static final int FLAG_GROUP_ADD_REMOVE = 0x01;

    /**
     * 群组增删群员管理员
     */
    public static final int FLAG_GROUP_ADD_REMOVE_MANMAGER = 0x02;

    protected Context mContext;
    protected Activity mActivity;
    protected HashMap<Integer, String> typeVisiableHashMap;
    protected int type;

    /**
     * 来自于某个界面不同的搜索栏类型
     */
    protected int flag = FLAG_MAIN;

    /**
     * 折叠控件
     */
    protected LinearLayout toggleView;
    protected int toggleHeight;

    /**
     * 滑动控件
     */
    protected RecyclerView slideView;

    /**
     * 搜索栏显示还是隐藏
     */
    protected boolean searchViewVisiable;

    @SuppressLint("UseSparseArrays")
    public SmoothToggleAndSlideAnimationForUI(Activity mActivity, int flag) {
        this.mContext = mActivity.getApplicationContext();
        this.mActivity = mActivity;
        this.flag = flag;
        this.toggleHeight = mActivity.getResources().getDimensionPixelSize(R.dimen.y100);
        this.typeVisiableHashMap = new HashMap<>();
        this.typeVisiableHashMap.put(0, HIDE);
        this.typeVisiableHashMap.put(1, HIDE);
        this.typeVisiableHashMap.put(2, HIDE);
    }

    public void setToggleView(LinearLayout toggleView) {
        this.toggleView = toggleView;
    }

    public void setSlideView(RecyclerView slideView, int type) {
        this.slideView = slideView;
        this.type = type;
        /**
         * 直接设置折叠控件高度
         * */
        String visiable = typeVisiableHashMap.get(type);
        if (!TextUtils.isTextEmpty(visiable)) {
            if (visiable.equals(HIDE)) {
                set(0);
            } else {
                set(toggleHeight);
            }
        }
    }

    /**
     * 判断当前是否未绑定滑动控件
     */
    public boolean isSlideViewNull() {
        return slideView == null;
    }

    /**
     * 判断当前搜索栏是否显示
     */
    public boolean isSearchViewVisiable() {
        return searchViewVisiable;
    }

    /**
     * 检测滑动与点击区分参数
     */
    private boolean downClicked;
    private long downTime;
    private long upTime;
    private boolean haveMoved;
    private float downX;
    private float downY;
    private final float slideGap = 5;

    private float dist(float x1, float y1, float x2, float y2) {
        float dist = 0.0f;
        float poorX = Math.abs(x2 - x1);
        float poorY = Math.abs(y2 - y1);
        dist = Math.abs(poorX * poorX + poorY * poorY);
        return dist;
    }

    /**
     * 触摸事件处理
     *
     * @param event
     */
    public boolean onTouchEvent(MotionEvent event) {
        try {
            int finngerSize = event.getPointerCount();
            if (finngerSize == 1) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        downClicked = true;
                        haveMoved = false;
                        downTime = System.currentTimeMillis();
                        downX = event.getX();
                        downY = event.getY();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        float moveX = event.getX();
                        float moveY = event.getY();
                        float dist = dist(downX, downY, moveX, moveY);
                        if (dist >= slideGap) {
                            haveMoved = true;
                            float poorY = (moveY - downY);
                            float poorX = (moveX - downX);
                            boolean dragUp = (poorY < 0);
                            // 上滑
                            if (dragUp) {
                            }
                            // 下滑
                            else {
                            }
                            if (Math.abs(poorY) >= Math.abs(poorX)) {
                                setToggleGradient((int) poorY, false);
                            }
                            downX = moveX;
                            downY = moveY;
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                        downClicked = false;
                        upTime = System.currentTimeMillis();
                        if (!haveMoved) {
                            boolean onlyClick = (upTime - downTime < 1000);
                            // 点击
                            if (onlyClick) {
                            }
                            // 长按
                            else {
                            }
                        } else {
                            // 移动弹起时，判断总移动距离是否大于折叠控件的一半高度，若达到则执行隐藏
                            setToggleGradient(0, true);
                        }
                        break;
                    default:
                        break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 动态设置折叠控件高度
     *
     * @param gradientHeight
     * @param upCheck
     */
    private void setToggleGradient(int gradientHeight, boolean upCheck) {
        if (toggleView == null) {
            return;
        }
        try {
            ViewGroup.LayoutParams layoutParams = toggleView.getLayoutParams();
            layoutParams.height += gradientHeight;
            if (layoutParams.height <= 0) {
                layoutParams.height = 0;
                typeVisiableHashMap.put(type, HIDE);
                searchViewVisiable = false;
            } else if (layoutParams.height >= toggleHeight) {
                layoutParams.height = toggleHeight;
                typeVisiableHashMap.put(type, SHOW);
                searchViewVisiable = true;
            }
            toggleView.setLayoutParams(layoutParams);
            if (upCheck) {
                int halfHeight = toggleHeight / 2;
                if (layoutParams.height < halfHeight) {
                    if (layoutParams.height > 0) {
                        new AnimationThread(10, 200, layoutParams.height, 0).start();
                    }
                } else {
                    if (layoutParams.height != toggleHeight) {
                        new AnimationThread(10, 200, layoutParams.height, toggleHeight).start();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 动画渐变线程
     */
    private class AnimationThread extends Thread {

        private int count; // 渐变次数
        private int milltimes; // 渐变总时长

        private int targetVal; // 目标值
        private int currentVal; // 当前值

        public AnimationThread(int count, int milltimes, int currentVal, int targetVal) {
            super();
            this.count = count;
            this.milltimes = milltimes;
            this.currentVal = currentVal;
            this.targetVal = targetVal;
        }

        @Override
        public void run() {
            super.run();
            try {
                boolean unit = currentVal > targetVal;
                int gap = (targetVal - currentVal) / count;
                if (Math.abs(gap) < 1) {
                    currentVal = targetVal;
                    set(currentVal);
                    return;
                } else {
                    int gapTime = milltimes / count;
                    for (int i = 0; i < (count + 3); i++) {
                        Thread.sleep(gapTime);
                        currentVal += gap;
                        if (unit) {
                            if (currentVal <= targetVal) {
                                currentVal = targetVal;
                                set(currentVal);
                                break;
                            } else {
                                set(currentVal);
                            }
                        } else {
                            if (currentVal >= targetVal) {
                                currentVal = targetVal;
                                set(currentVal);
                                break;
                            } else {
                                set(currentVal);
                            }
                        }
                    }
                    if (currentVal != targetVal) {
                        currentVal = targetVal;
                        set(currentVal);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 设置当前数值
     *
     * @param afterGradientHeight
     */
    public void set(int afterGradientHeight) {
        mActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ViewGroup.LayoutParams layoutParams = toggleView.getLayoutParams();
                layoutParams.height = afterGradientHeight;
                toggleView.setLayoutParams(layoutParams);
                searchViewVisiable = (afterGradientHeight == 0);
                typeVisiableHashMap.put(type, searchViewVisiable ? HIDE : SHOW);
            }
        });
    }

}
